package cn.easybuy.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.easybuy.dao.BaseDao;
import cn.easybuy.dao.UserDao;
import cn.easybuy.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao{

	@Override
	public int saveUser(User user) {
		String sql="insert into easybuy_user(loginName,userName,password,sex,identityCode,email,mobile,type) values(?,?,?,?,?,?,?,?)";
		Object[] objects={user.getLoginName(),user.getUserName(),user.getPassword(),user.getSex(),user.getIdentityCode(),user.getEmail(),user.getMobile(),user.getType()};
		int num=this.executeUpdate(sql, objects);
		return num;
	}

	@Override
	public List<User> getUsersByLoginName(String loginName) { //验证注册登录名是否重复
		String sql="select userName from easybuy_user where loginName=?";
		ResultSet rs=this.exxcuteQuery(sql, loginName);
		List<User> list=new ArrayList<User>();
		try {
			while (rs.next()) {
				User user = new User();
				user.setUserName(rs.getString(1));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection, pstmt, rs);
		}
		return list;
	}

	@Override
	public List<User> getUsersForLogin(String loginName, String password) {
		String sql="select userName from easybuy_user where loginName=? and password=?";
		ResultSet rs=this.exxcuteQuery(sql, loginName,password);
		List<User> list=new ArrayList<User>();
		try {
			while (rs.next()) {
				User user = new User();
				user.setUserName(rs.getString(1));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection, pstmt, rs);
		}
		return list;
	
	}

	@Override
	public List<User> getUsersPage(int currNo, int pageSize) {
		String sql="select * from easybuy_user order by id limit ?,?";
		ResultSet rs=this.exxcuteQuery(sql, (currNo-1)*pageSize,pageSize);
		List<User> list=new ArrayList<User>();
		try {
			while (rs.next()) {
				User user=new User();
				user.setId(rs.getInt(1));
				user.setLoginName(rs.getString(2));
				user.setUserName(rs.getString(3));
				user.setPassword(rs.getString(4));
				user.setSex(rs.getInt(5));
				user.setIdentityCode(rs.getString(6));
				user.setEmail(rs.getString(7));
				user.setMobile(rs.getString(8));
				user.setType(rs.getInt(9));
				list.add(user);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection, pstmt, rs);
		}
		return list;
	}

	@Override
	public int getTotalCount() {
		String sql="select count(1) from easybuy_user";
		ResultSet rs=this.exxcuteQuery(sql);
		int totalCount=0;
		try {
			while (rs.next()) {
				totalCount=rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection, pstmt, rs);
		}
		return totalCount;
	}
	

}
